<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item>轮播图管理</el-breadcrumb-item>
    <el-breadcrumb-item>添加轮播图</el-breadcrumb-item>
  </el-breadcrumb>

  <el-form
    :model="ruleForm"
    class="demo-ruleForm"
    :rules="rules"
    ref="ruleFormRef"
    label-position="right"
    label-width="200px"
  >
    <el-form-item prop="link" label="链接地址">
      <el-input v-model="ruleForm.link" placeholder="链接地址" />
    </el-form-item>
    <el-form-item prop="alt" label="提示">
      <el-input v-model="ruleForm.alt" placeholder="提示" />
    </el-form-item>

    <el-form-item label="图片">
      <input type="file" @change="fileChange" />
    </el-form-item>

    <el-form-item>
      <el-image
        style="width: 200px; height: 200px"
        :src="imgurl"
        :preview-src-list="[imgurl]"
        fit="cover"
        :preview-teleported="true"
        v-if="imgurl"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, render } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

import { addBannerApi } from "@/api/banner";

const router = useRouter();

interface RuleForm {
  link: string;
  alt: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  link: "",
  alt: "",
});

const rules = reactive<FormRules<RuleForm>>({
  link: [{ required: true, message: "请输入链接地址", trigger: "blur" }],
  alt: [{ required: true, message: "请输入提示", trigger: "blur" }],
});

const imgurl = ref("");

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // console.log({ ...ruleForm, img: imgurl.value });
      const res = await addBannerApi({ ...ruleForm, img: imgurl.value });
      if (res) {
        ElMessage.success("插入成功");
        router.push("/home/bannerlist");
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const fileChange = (e: Event) => {
  // console.log((e.target as HTMLFormElement).files[0]);
  // 将文件转成base64格式
  const reader = new FileReader();
  reader.readAsDataURL((e.target as HTMLFormElement).files[0]);
  reader.onload = (event: any) => {
    // console.log(event.target.result);
    imgurl.value = event.target.result;
  };
};
</script>

<style lang="less" scoped>
.el-form {
  width: 600px;
}
</style>
